﻿using System.Collections.ObjectModel;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using Labthink.PCSoft.UniversalHost4.Model.Setting;
using Labthink.PCSoft.UniversalHost4.Utility;

namespace Labthink.PCSoft.UniversalHost4.UserControls
{
    public partial class UcParamTrace
    {
        private readonly ObservableCollection<ParamForTrace> _listUnTraced;
        private readonly ObservableCollection<ParamForTrace> _listTraced;
        private bool _origin;
        private ParamForTrace _data;
        private FrameworkElement _dragScope;
        private DragAdorner _adorner;
        private AdornerLayer _layer;
        private NotifyManager _notify;

        public UcParamTrace()
        {
            InitializeComponent();
            _listUnTraced = new ObservableCollection<ParamForTrace>();
            _listTraced = new ObservableCollection<ParamForTrace>();
        }

        private void SelectedData_OnDrop(object sender, DragEventArgs e)
        {
            IDataObject da = e.Data;
            if (da.GetDataPresent(typeof(ParamForTrace)))
            {
                if (_origin)
                {
                    Loading.Visibility = Visibility.Visible;
                    var r = _remove(_data);
                    if (r >= 0)
                    {
                        _listTraced.Remove(_data); //添加
                        _listUnTraced.Add(_data); //删除
                    }

                    Loading.Visibility = Visibility.Collapsed;
                }
            }

            ShowData.BorderBrush = Brushes.Gray;
            SData.BorderBrush = Brushes.Gray;
        }

        private void SelectedData_OnDragLeave(object sender, DragEventArgs e)
        {
            SData.BorderBrush = Brushes.Gray;
        }

        private void UIElement_OnPreviewMouseMove(object sender, MouseEventArgs e)
        {
            if (sender is TextBlock textBlock)
            {
                int id = (int)textBlock.Tag;
                //startP = e.GetPosition(canvas1);
                //string name = (string)(sender as TextBlock).Name;
                //user = getUser(name);
                _data = _findData(id);
            }

            if (e.LeftButton == MouseButtonState.Pressed)
            {
                _startMove(sender as TextBlock);
            }
        }

        private void _startMove(TextBlock t)
        {
            //实现拖拽的动画效果，画面不是很明显，要细看
            try
            {
                _dragScope = Application.Current.MainWindow.Content as FrameworkElement;
                if (_dragScope != null)
                {
                    _dragScope.AllowDrop = true;
                    DragEventHandler draghandler = (DragScope_PreviewDragOver);
                    _dragScope.PreviewDragOver += draghandler;
                    _adorner = new DragAdorner(_dragScope, t, 0.5);
                    _layer = AdornerLayer.GetAdornerLayer(_dragScope);
                    _layer.Add(_adorner);
                    DataObject data = new DataObject(typeof(ParamForTrace), _data);
                    DragDrop.DoDragDrop(t, data, DragDropEffects.Move);
                    AdornerLayer.GetAdornerLayer(_dragScope).Remove(_adorner);
                    _adorner = null;
                    _dragScope.PreviewDragOver -= draghandler;
                }
            }
            catch
            {
                // ignored
            }
        }

        void DragScope_PreviewDragOver(object sender, DragEventArgs args)
        {
            if (_adorner != null)
            {
                _adorner.LeftOffset = args.GetPosition(_dragScope).X;
                _adorner.TopOffset = args.GetPosition(_dragScope).Y;
            }
        }

        private ParamForTrace _findData(int id)
        {
            //判断拖动源，来自list1还是list2
            //Rectangle list1Rec = new Rectangle();
            if (ShowData.IsMouseCaptured)
            {
                ShowData.BorderBrush = Brushes.Coral;
                _origin = true;
                foreach (var u in _listTraced)
                {
                    if (u.DataNo == id)
                        return u;
                }
            }

            else if (SData.IsMouseCaptured)//单击捕获
            {
                SData.BorderBrush = Brushes.Coral;
                _origin = false;//判断元素来源
                foreach (var usr in _listUnTraced)
                {
                    if (usr.DataNo == id)
                    {
                        return usr;
                    }
                }
            }

            return null;
        }

        private void Data_OnDragOver(object sender, DragEventArgs e)
        {
            if (!_origin)
                ShowData.BorderBrush = Brushes.Coral;
            else
                SData.BorderBrush = Brushes.Coral;

            if (!e.Data.GetDataPresent(typeof(ParamForTrace)))
            {
                e.Effects = DragDropEffects.None;//放置目标不接受该数据
                e.Handled = true;
            }
        }

        private void ShowData_OnDrop(object sender, DragEventArgs e)
        {
            IDataObject da = e.Data;
            if (da.GetDataPresent(typeof(ParamForTrace)))
            {
                if (!_origin)
                {
                    Loading.Visibility = Visibility.Visible;
                    var r = _insert(_data);
                    if (r >= 0)
                    {
                        _listUnTraced.Remove(_data);
                        _listTraced.Add(_data);
                    }

                    Loading.Visibility = Visibility.Collapsed;
                }
            }

            ShowData.BorderBrush = Brushes.Gray;
            SData.BorderBrush = Brushes.Gray;
        }

        private void ShowData_OnDragLeave(object sender, DragEventArgs e)
        {
            ShowData.BorderBrush = Brushes.Gray;
        }

        private void Back_OnClick(object sender, RoutedEventArgs e)
        {
            if (!(ShowData.SelectedItem is ParamForTrace fd)) return;
            Loading.Visibility = Visibility.Visible;
            var r = _remove(fd);
            if (r >= 0)
            {
                _listTraced.Remove(fd);
                _listUnTraced.Add(fd);
                _notify.ShowSuccess(LanguageManager.GetLanguageValue("ActionSuccess"));
            }
            else
            {
                _notify.ShowError(LanguageManager.GetLanguageValue("ActionFail"));
            }
            Loading.Visibility = Visibility.Collapsed;
        }

        private void Go_OnClick(object sender, RoutedEventArgs e)
        {
            if (!(SData.SelectedItem is ParamForTrace fd)) return;
            Loading.Visibility = Visibility.Visible;
            var r = _insert(fd);
            if (r >= 0)
            {
                _listUnTraced.Remove(fd);
                _listTraced.Add(fd);
                _notify.ShowSuccess(LanguageManager.GetLanguageValue("ActionSuccess"));
            }
            else
            {
                _notify.ShowError(LanguageManager.GetLanguageValue("ActionFail"));
            }

            Loading.Visibility = Visibility.Collapsed;
        }

        private int _insert(ParamForTrace pft)
        {
            return 0;

            //var sd = await _commands.InsertOneParamForTraceAsync(pft);
            //return sd.ErrorCode;
        }

        private int _remove(ParamForTrace pft)
        {
            return 0;

            //var sd = await _commands.RemoveOneParamForTraceAsync(pft);
            //return sd.ErrorCode;
        }

        private void ParamTrace_OnLoaded(object sender, RoutedEventArgs e)
        {
            return;

            //var w = Window.GetWindow(this);
            //_notify = NotifyManager.InstanceManager(w);


            //_listTraced.Clear();
            //_listUnTraced.Clear();
            //var sd = await _commands.GetParamsForTraceAsync();
            //var allparams = JsonConvert.DeserializeObject<List<ParamForTrace>>(sd.Value);
            //sd = await _commands.GetTracedParamsAsync();
            //var tracedParams = JsonConvert.DeserializeObject<List<ParamForTrace>>(sd.Value);
            //_listTraced.AddRange(tracedParams);
            //foreach (var param in allparams)
            //{
            //    if (tracedParams.All(p => p.DataNo != param.DataNo)) _listUnTraced.Add(param);
            //}

            //SData.ItemsSource = _listUnTraced;
            //ShowData.ItemsSource = _listTraced;
        }

        public string Title { get; set; } = LanguageManager.GetLanguageValue("ParamTrace");
        public string PermissionCode { get; set; } = "Per_ParamTrace";
    }
}
